package com.wzh.service.Impl;

import com.google.common.collect.Lists;
import com.wzh.entity.dto.QueryDto;
import com.wzh.exception.MyException;
import com.wzh.mapper.ClothesMapper;
import com.wzh.mapper.CustomerMapper;
import com.wzh.entity.dto.ColorsDto;
import com.wzh.entity.dto.OrderDto;
import com.wzh.entity.dto.SizesDto;
import com.wzh.entity.po.*;
import com.wzh.entity.Resp.DataResp;
import com.wzh.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ClothesMapper clothesMapper ;

    @Override
    public DataResp<Object> newCustomer(Customer customer) {
        DataResp<Object> resp = new DataResp<>();

        if(customer.getId()==null){
            customer.setId(System.currentTimeMillis());
        }
        customerMapper.newCustomer(customer);
        return resp;
    }


    @Override
    public DataResp<Object> myCustomer(QueryDto queryDto) {
        DataResp<Object> resp = new DataResp<>();
        if(queryDto.getIndex()!=0){
            Integer index =queryDto.getIndex()* queryDto.getCount();
            queryDto.setIndex(index);
        }
        Integer counts= customerMapper.selectMyCustomerCount(queryDto);

        List<Customer> customerList = customerMapper.selectMyCustomer(queryDto);
        resp.setPageCount(counts);
        resp.setData(customerList);
        return resp;
    }

    @Override
    @Transactional(rollbackFor = MyException.class)
    public DataResp<Object> newOrder(OrderDto orderDto) {
        DataResp<Object> resp = new DataResp<>();
        //组装参数
        List<SalesItem> salesItems = new ArrayList<SalesItem>();
        HashMap<String,Object> map =new HashMap<>();
        List<SalesItem> salesItemsNum = new ArrayList<SalesItem>();
        Long id =System.currentTimeMillis();
        map.put("id",id);
        map.put("salesTime",orderDto.getSalesTime());
        map.put("companyId",orderDto.getCompanyId());
        map.put("customerId",orderDto.getCustomerId());
        map.put("receivableAmount",orderDto.getReceivableAmount());
        map.put("paidAmount",orderDto.getPaidAmount());
        customerMapper.newOrder(map);
        for (ColorsDto colorsDto : orderDto.getColorsDtos()
        ) {

            for (SizesDto sizesDto:colorsDto.getSizeDtos()
            ) {

                if(sizesDto.getMount()>0){
                    SalesItem salesItem=new SalesItem();
                    salesItem.setSalesId(id);
                    salesItem.setClothesId(orderDto.getClothesId());
                    salesItem.setCompanyId(orderDto.getCompanyId());
                    salesItem.setColorName(colorsDto.getColorName());
                    salesItem.setSizeName(sizesDto.getSizeName());
                    salesItem.setNum(sizesDto.getMount());
                    salesItems.add(salesItem);
                }
            }
        }

        //校验库存信息
        List<colorAndNum> colorAndNumList =clothesMapper.findColorAndNum(orderDto.getClothesId());

        //去重 可能存在补货（相同的颜色尺码的生产任务）
        for (colorAndNum colorAndNum:colorAndNumList
        ) {
            colorAndNum.setSizeAndNumList(clothesMapper.getSizeAndNum(colorAndNum));
        }

        if (colorAndNumList.size()==0){
            throw new MyException(202,"库存为空,请检查库存信息");
        }
        Map<String,List<SizeAndNum>> data = new HashMap<>();
        for (colorAndNum item:colorAndNumList){
            data.put(item.getColorName(),item.getSizeAndNumList());
        }

        for (SalesItem salesItem:salesItems){
            if (!data.containsKey(salesItem.getColorName())){
                throw new MyException(203,salesItem.getColorName()+"款式未入库,请检查库存信息");
            }
            int count=0;//当前总库存
            for (SizeAndNum sizeAndNum:data.get(salesItem.getColorName())){
                if (sizeAndNum.getSizeName().equals(salesItem.getSizeName()) ){
                    count+=sizeAndNum.getRealNum();
                }
            }

            if(salesItem.getNum()>count){
                throw new MyException(204,salesItem.getColorName()+salesItem.getSizeName()+"库存不足,请检查库存信息");
            }else{
                //随机减库存
                for (SizeAndNum sizeAndNum:data.get(salesItem.getColorName())){
                    if (sizeAndNum.getSizeName().equals(salesItem.getSizeName())&&sizeAndNum.getRealNum()>0){
                        if(count>sizeAndNum.getRealNum()){
                            clothesMapper.delTaskMountById(sizeAndNum.getId(),sizeAndNum.getRealNum());
                            count-=sizeAndNum.getRealNum();
                        }else{
                            clothesMapper.delTaskMountById(sizeAndNum.getId(),count);
                        }

                    }
                }

            }

        }
        customerMapper.newOrderItem(salesItems);





        return resp;
    }

    @Override
    public DataResp<Object> myCustomerOrder(Long id) {
        DataResp<Object> resp = new DataResp<>();

        List<Sales> sales =customerMapper.findSales(id);
        if(sales.size()==0){
            resp.setData(null);
            return resp;
        }

        //去重 可能存在补货（相同的颜色尺码的生产任务）
        for (Sales item:sales
        ) {
           item.setSalesItemList(customerMapper.findSalesItemById(item.getId()));
           item.setClothes(clothesMapper.selectClothesInfo(item.getSalesItemList().get(0).getClothesId()));
        }


        Map<String,String> colorMap =new HashMap<>();
        Map<String,String> sizeMap =new HashMap<>();
        for (Sales item:sales
        ) {
            for (SalesItem salesItem:item.getSalesItemList()
            ) {
                colorMap.put(salesItem.getColorName(),salesItem.getColorName());
                sizeMap.put(salesItem.getSizeName(),salesItem.getSizeName());
            }
        }

        List<String> title = new ArrayList<>();//表头数据
        title.add("颜色/尺码");
        for(String obj:sizeMap.keySet()){
            title.add(sizeMap.get(obj));
        }


        for (Sales item:sales
        ) {
            List<List<String>> finalData=new ArrayList<>();
            StringBuilder stringBuilderContent = new StringBuilder();


                for (SalesItem salesItem:item.getSalesItemList()
                ) {
                    List<String> content = Lists.newArrayList();//行数据
                    content.add(salesItem.getColorName());
                    for (int i = 1; i < title.size(); i++) {
                        int count =0;
                         if(title.get(i).equals(salesItem.getSizeName())){
                         count=salesItem.getNum();
                     }
                        content.add(String.valueOf(count));
                    }
                    finalData.add(content);

                }
            stringBuilderContent.append("<html><head></head><body><h2></h2>");
            stringBuilderContent.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size=14px;;font-size:22px;\">");
            //构造html
            stringBuilderContent.append("<tr style=\"background-color: #428BCA; color:#ffffff\">");

            for (String titleName:title
            ) {
                stringBuilderContent.append("<th width=\"280px\">"+titleName+"</th>");
            }
            stringBuilderContent.append("</tr>");

            for (List<String> item3:finalData
            ) {
                stringBuilderContent.append("<tr>");
                for (String item4:item3
                ) {
                    stringBuilderContent.append("<td style=\"text-align:center\">" +item4 + "</td>");
                }
                stringBuilderContent.append("</tr>");
            }
            stringBuilderContent.append("</table>");
            stringBuilderContent.append("</body></html>");
            item.setHtml(stringBuilderContent);
            }

        resp.setData(sales);
        return resp;
    }

    @Override
    public DataResp<Object> payFor(Sales sales) {
        DataResp<Object> resp = new DataResp<>();

        customerMapper.payFor(sales);
        return resp;
    }

    @Override
    public DataResp<Object> myCustomerInfo(Long id) {
        DataResp<Object> resp = new DataResp<>();
        Customer customer =customerMapper.myCustomerInfo(id);
        resp.setData(customer);
        return resp;
    }

    @Override
    public DataResp<Object> delCustomer(Long id) {
        DataResp<Object> resp = new DataResp<>();
       customerMapper.delCustomer(id);

        return resp;
    }

    @Override
    public DataResp<Object> myCustomerDetail(Customer customer) {
        DataResp<Object> resp = new DataResp<>();
        List<Customer> customerList = customerMapper.selectMyCustomerDetail(customer);
        resp.setData(customerList);
        return resp;
    }
}
